package com.zl.auth.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zl.auth.client.utils.HttpClientUtil;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Controller
public class RouterController {
    @RequestMapping("client/index")
    public String index(){
        return "index";
    }

    @RequestMapping("client/toLogin")
    public String toLogin(){
        return "toLogin";
    }

    @RequestMapping("client/fetchCode")
    public String fetchCode(String code, HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> params = new HashMap();
        params.put("grant_type","authorization_code");
        params.put("redirect_uri","http://localhost:18091/client/fetchCode");
        params.put("code",code);
        Header h = new BasicHeader("Authorization", "Basic "+Base64Utils.encodeToString("free-web:123456".getBytes()));
        String result = HttpClientUtil.sendPostForm("http://localhost:18092/oauth/token", params,new ArrayList<Header>(){{this.add(h);}}, null);
        System.out.println(result);
        if (result != null){
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getString("access_token") != null){
                String token = jsonObject.getString("access_token");
                params = new HashMap<>();
                params.put("access_token",token);
                String res = HttpClientUtil.sendPostForm("http://localhost:18092/autu/getUserInfo", params, null, null);
                System.out.println(res);
                request.getSession().setAttribute("userinfo",res);
                Cookie cookie = new Cookie("access_token",token);
                cookie.setHttpOnly(false);
                cookie.setMaxAge(7200);
                cookie.setPath("/");
                cookie.setDomain("localhost");
                response.addCookie(cookie);
                return "redirect:index";
            }
        }
        return "client/error";
    }
}
